package tech.yunland.shop.domain.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tech.yunland.shop.domain.dao.LessonsDao;
import tech.yunland.shop.domain.model.Lessons;

import java.math.BigInteger;
import java.util.List;
import java.util.Map;

/**
 * Created by v on 17-7-3.
 */
@Service
public class LessonsServiceImpl implements LessonsService {
    @Autowired
    private LessonsDao lessonsDao;

    @Override
    public void save(Lessons lessons) {
        lessonsDao.save(lessons);
    }

    @Override
    public Integer getSize(String param) {
        String sql =
                "select count(1) counts\n" +
                        "from\n" +
                        "lessons l\n";
        if (param != null) {
            sql += "where l.lname like '%" + param + "%'";
        }
        int counts = ((BigInteger) lessonsDao.findUniqueBySQL(sql).get("counts")).intValue();
        return counts;
    }

    @Override
    public List<Map<String, Object>> get(String param, Integer startIdx, Integer rows) {
        String sql = "SELECT * FROM lessons l";
        if (param != null) {
            sql += " where l.lname like '%" + param + "%'";
        }
        return lessonsDao.findBySQL(sql, startIdx, rows);
    }

    @Override
    public Integer getLessonsSize(String uid) {
        String sql =
                "select count(1) counts\n" +
                        "FROM lessons l\n" +
                        "WHERE l.id IN (SELECT ul.lessons_id\n" +
                        "               FROM user_lessons ul\n" +
                        "               WHERE ul.students_id = '" + uid + "')";
        int counts = ((BigInteger) lessonsDao.findUniqueBySQL(sql).get("counts")).intValue();
        return counts;
    }

    @Override
    public List<Map<String, Object>> getLessons(String uid, Integer startIdx, Integer rows) {
        String sql =
                "SELECT *\n" +
                        "FROM lessons l\n" +
                        "WHERE l.id IN (SELECT ul.lessons_id\n" +
                        "               FROM user_lessons ul\n" +
                        "               WHERE ul.students_id = '" + uid + "')";
        return lessonsDao.findBySQL(sql, startIdx, rows);
    }


}
